from rest_framework import serializers
from areas.models import Area
from users.models import Address
import re


class AreasSerializer(serializers.ModelSerializer):
    class Meta:
        model = Area
        fields = ('id','name')

# 地址管理
class AddressSerializers(serializers.ModelSerializer):
    # 显示指明
    city = serializers.StringRelatedField(read_only=True) # 需要返回给前端 进行序列化返回
    district =serializers.StringRelatedField(read_only=True)
    province = serializers.StringRelatedField(read_only=True)
    city_id = serializers.IntegerField(write_only=True) # 不进行返回操作 参与返序列化过程
    district_id = serializers.IntegerField(write_only=True)
    province_id = serializers.IntegerField(write_only=True)

    class Meta:
        model = Address
        fields = (
            'city_id','district_id','province_id','email','mobile','place',
            'receiver','tel','title','city','province','district','id'
        )


    # 验证手机号格式
    def validate_mobile(self, value):
        if not re.match(r'^1[3-9]\d{9}$', value):
            raise serializers.ValidationError('手机号不匹配')

        return value

    # 获取用户对象
    def create(self, validated_data):
        user = self.context['request'].user
        validated_data['user'] = user
        address = Address.objects.create(**validated_data)
        return address